<?php
/*
 * File: PaymentController.php
 * Project: NewDemo
 * Created Time: 2024-07-05 03:21:39 pm
 * Author: WangYuQiang && WangpeiGang (719404171@qq.com)
 * -----
 * Last Modified: 2025-04-02 10:54:31 am
 * Modified By: WangYuQiang (719404171@qq.com>)
 * -----
 * Copyright (c) 2023 - 2024 成都睿創科技有限公司
 */

namespace App\Http\Controllers\Api;
use App\Models\User;
use App\Models\Order;
use App\Models\Coupon;
use App\Models\Product;
use App\Models\UserCart;
use App\Models\SystemInfo;
use App\Models\OrderDetails;
use App\Models\ProductRelation;
use App\Models\UserWalletRecord;
use App\Models\UserIntegralRecord;
use PayPal\Api\Item;
use PayPal\Api\Sale;
use PayPal\Api\Payer;
use PayPal\Api\Refund;
use PayPal\Api\Amount;
use PayPal\Api\Payment;
use PayPal\Api\Details;
use PayPal\Api\ItemList;
// use PayPal\Api\Discount;
use PayPal\Rest\ApiContext;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\ExecutePayment;
use PayPal\Api\ShippingAddress;
use PayPal\Api\PaymentExecution;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Exception\PayPalConnectionException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Notifications\Notifiable;
//Stripe
use Stripe\Customer;
use Stripe\Checkout\Session;
use Laravel\Cashier\Cashier;
use Laravel\Cashier\Checkout;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\MailController;
use App\Http\Controllers\Common\GeTuiController;


class PaymentController extends Controller{

    private $clientId;
    private $clientSecret;
    private $apiContext;
    private $UserCart;
    private $Coupon;
    private $Order;
    private $User;
    
    
    public function __construct(){
        $this->UserCart = new UserCart();
        $this->Coupon = new Coupon();
        $this->Order = new Order();
        $this->User = new User();
        // paypal支付回調-成功鏈接
        $this->paypal_callback_success = config('services.basics.base_uri').'/api/PaypalCallbackSuccess';
        // paypal支付回調-失敗鏈接
        $this->paypal_callback_error = config('services.basics.base_uri').'/api/PaypalCallbackError';
        // Stripe支付
        $this->stripe_payment= config('services.basics.base_uri').'/api/StripePayment';
        // Stripe支付回調-成功鏈接
        $this->stripe_callback_success = config('services.basics.base_uri').'/api/StripeCallbackSuccess';
        // Stripe支付回調-失敗鏈接
        $this->stripe_callback_error = config('services.basics.base_uri').'/api/StripeCallbackError';
        // 支付成功鏈接
        $this->success_uri = config('services.basics.base_uri').'/api/success';
        // 支付失敗鏈接
        $this->error_uri = config('services.basics.base_uri').'/api/error';
        //設置支付成功返回語言
        $this->language = app('global_language')  == "en" ? "en" : "zh";

        // paypal支付設置
        if (app('global_paypal_env') == 1) {
            $this->mode = 'live';
        }else{
            $this->mode = 'sandbox';
        }
        $this->clientId = app('global_client_id');
        $this->clientSecret = app('global_paypal_secret');
        $this->apiContext = new ApiContext(
            new OAuthTokenCredential(
                $this->clientId,
                $this->clientSecret
            )
        );

        $this->apiContext->setConfig(array(
                'mode' => $this->mode,//支付環境
                'log.LogEnabled' => true,
                'log.FileName' => '../storage/logs/PayPal.log',
                'log.LogLevel' => 'FINE',
                'cache.enabled' => false
            ));
    }


    
/**************************************************產品支付*************************************************************************/

    /**
     * @param Request $request
     * @return array
     * 產品支付
     */
    public function PurchaseProduct(Request $request){
        //接收参数
        $info=$request->post();
        // 优惠金额设置
        $info['coupon_money'] = 0 ;
        // 订单原价
        $info['original_cost'] =  $info['order_money']; 
        //用户id
        $info['user_id']=auth('api')->user()->user_id;
        //判斷產品庫存，如果不足
        if($info['payment_type']==1 && $info['indent_type']==1 ){
            foreach ($info['product'] as $key => $value) {
                $product_number=$info['product'][$key]['product_number'];
                $Relationinfo=ProductRelation::where('product_relation_id',$info['product'][$key]['product_relation_id'])->select('stock')->first();
                if(!empty($Relationinfo)){
                    $RelationStock=$Relationinfo['stock'];
                    if($RelationStock<$product_number){
                        return $this->error(__('api.Stock_fail'));
                    }
                }           
            }
        }
        //刪除購物車
        if(!empty($info['cart_id'])){
            $this->UserCart->DeleteShoppingCart($info['cart_id']);
        }
         //立即支付 && 产品&& 商家发货 才有运费 其他的设置运费为0
        if($info['payment_type']==1 && $info['indent_type']==1 && $info['receiving_type']==1 ){
            $info['freight_price'] = app('global_freight_price');  
        }
        //预约到店金额设置
        if($info['payment_type']== 2 ){
            //最小支付金额
             $info['booking_price'] = empty( app('global_tostore_price') ) ? 0.01 : app('global_tostore_price');
             $info['original_cost'] = $info['booking_price'];//訂單原价=订单实际支付金额+订单优惠金额
             $info['order_money'] = $info['booking_price'];//订单支付金额
             $info['freight_price'] = 0;  
        }
        //优惠券和支付金额处理
        if(!empty($info['coupon_id'])){
            $Check['user_id']=$info['user_id'];
            $Check['coupon_id']=$info['coupon_id'];
            $Check['original_cost']=$info['original_cost'];
            //檢測優惠券是否可用
            $ResultCheck=$this->Coupon->OrderCheckCoupon($Check);
            if(empty($ResultCheck)){
                return $this->error(__('api.coupon_fail'));
            }else{
                $discount=$this->discountPrice($Check);
                $info['original_cost']=$discount['original_cost'];
                $info['coupon_money']=$discount['coupon_money'];
                $info['order_money']=$discount['order_money'];
            }
        }
        //处理参数,生成訂單信息
        $OrderId= $this->Order->generateOrder($info); //获取 Order ID
        if (empty($OrderId)) {
            //訂單參數錯誤
            return $this->parametersError(__('api.order_error'));
        }
        //添加订单详情
        $product['ProductInfo']=$info['product'];
        $product['coupon_id']=$info['coupon_id'];
        $product['user_id']=$info['user_id'];
        $product['receiving_type']=$info['receiving_type'];
        $product['order_id']=$OrderId;
        $OrderDetails = $this->Order->setDetailsOrder($product); //設置订单详情
        if (empty($OrderDetails)){
            //訂單詳情參數錯誤
            return $this->parametersError(__('api.details_error'));
        }
        //支付所需參數
        $payment['order_id']=$OrderId;
        //支付
        if($info['payment_mode']==1){
            // 支付方式: 1：paypal  
            return $this->PaypalPayment($payment);
        }elseif ($info['payment_mode']==2) {
            // 支付方式:   2：Stripe
            $result['url']=$this->stripe_payment."?order_id=".$payment['order_id'];
            return $result;
        }elseif ($info['payment_mode']==3) {
            // 支付方式: 3：錢包
            return $this->BalancePayment($payment);
        }elseif ($info['payment_mode']==4) {
            // 支付方式: 4：其他支付（上傳支付圖片）
            return $this->OtherPayment($payment);
        }
    }


/**************************************************商品折扣優惠券計算*******************************************************************************/
    /**
     * @param Request $request
     * @return array
     * 商品折扣優惠券計算
     * $data['coupon_id']
     * $data['original_cost']
     */
    public function discountPrice($data){
        $coupon = Coupon::where('coupon_id',$data['coupon_id'])->select('coupon_type','discount')->first();
            switch ($coupon['coupon_type']) {
                case '1':
                    $coupon_money =  $coupon['discount'];
                    break;
                case '2':
                    $coupon_money =  $coupon['discount'];
                    break;
                case '3':
                    $coupon_money = $data['original_cost'] *( 1 - $coupon['discount'] );
                    break;
                case '4':
                    $coupon_money = $data['original_cost'] * ( 1 - $coupon['discount'] );
                    break;
            }
        if($coupon_money>=$data['original_cost']){
            $result['coupon_money']= $data['original_cost']-0.01;
        }else{
            $result['coupon_money']= $coupon_money;
        }
        $result['original_cost']= $data['original_cost'];
        $result['order_money']=$data['original_cost'] - $result['coupon_money'] ;
        return $result;   
    }


    
/**************************************************订单去支付*************************************************************************/

    /**
     * @param Request $request
     * @return array
     * 订单去支付
     * $info['order_id']
     * $info['payment_mode']
     */
    public function PaymentOrder(Request $request){
        //接收参数
        $info=$request->post();
        $orderinfo = Order::where('order_id',$info['order_id'])->select('payment_status','order_money')->first()->toArray();
        if( $orderinfo['payment_status']> 2 ){
            return $this->error(__('api.payment_error'));
        }
         //更新訂單支付方式
         $PaymentMode=Order::where('order_id',$info['order_id'])->update(['payment_mode'=> $info['payment_mode'],'updated_at'=>date('Y-m-d H:i:s')]);
        //订单id
        $payment['order_id']=$info['order_id'];
        if($info['payment_mode']==1){
            // 支付方式: 1：paypal  
            return $this->PaypalPayment($payment);
        }elseif ($info['payment_mode']==2) {
            // 支付方式:   2：Stripe
            //Stripe支付最小金額為4元
            if($orderinfo['order_money'] < 4 ){
                return $this->error(__('api.stripe_lowest'));
            }
            $result['url']=$this->stripe_payment."?order_id=".$payment['order_id'];
            return $result;
            return $this->StripePayment($payment);
        }elseif ($info['payment_mode']==3) {
            // 支付方式: 3：錢包
            return $this->BalancePayment($payment);
        }elseif ($info['payment_mode']==4) {
            // 支付方式: 4：其他支付（上傳支付圖片）
            return $this->OtherPayment($payment);
         }
    }


/**************************************************支付方式-錢包支付*************************************************************************/
    /**
     * @param Request $request
     * @return array
     * 支付方式--錢包支付
     * data['order_id']
     */
    public function BalancePayment($data){
        // 獲取訂單信息
        $orderinfo = Order::where('order_id',$data['order_id'])->select('order_id','user_id','order_money')->first()->toArray();
        $userinfo = User::where('user_id', $orderinfo['user_id'])->select('user_balance')->first()->toArray();
        if( ($userinfo['user_balance'] - $orderinfo['order_money']) >= 0 ){
            DB::beginTransaction();
            //修改賬戶餘額
            $userBalance = User::where('user_id',$orderinfo['user_id'])->decrement('user_balance',$orderinfo['order_money']);
            //支付完成更改訂單信息
            $effects=$this->paymentComplete($orderinfo['order_id'],$orderRefundId='');
            if(!empty($effects)){
                //支付完成後操作(推送 郵箱 系統消息  )
                $solution=$this->OrderComplete($orderinfo['order_id']);
                $results['orderId']=$orderinfo['order_id'];
                $results['Url']=$this->success_uri;
                DB::commit();
                return $this->success(__('api.balance_success'),$results);
            }else{
                // 支付不成功，退款
                DB::rollBack();
                $results['orderId']=$orderinfo['order_id'];
                $results['Url']=$this->error_uri;
                return $this->error(__('api.balance_error'),$results);
            }
        }else{
            //錢包餘額不足，請充值或者選擇其他支付方式
            return $this->error(__('api.balance_fail'));
        }    
    }



/**************************************************支付方式-Paypal支付*************************************************************************/
    /**
     * @param Request $request
     * @return array
     * 支付方式--Paypal支付
     * data['order_id']
     */
    public function  PaypalPayment($data){
        $result=$this->paymentNow($data['order_id']); 
        return $result;
    }

    /**
     * @param $item
     * @param $address
     * @param $money
     * @param $orderid
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * 調起支付
     */
    public function paymentNow($orderid){
        $orderinfo = Order::where('order_id',$orderid)->select('*')->first()->toArray();
        $detailsinfo = OrderDetails::where('order_id',$orderid)->select('*')->get()->toArray();
        // 创建支付对象
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');
        // 支付类型：1：立即支付，2：預約到店查看
        if($orderinfo['payment_type']==1){
            if($orderinfo['order_money']==0.01){
                // 创建项目列表
                $item = new Item();
                $item->setName($detailsinfo[0]['product_name'])->setCurrency('HKD')->setQuantity(1)->setPrice((int)0.01);
                $itemList = new ItemList();
                $itemList->setItems([$item]);
            }else{
                // 创建多个项目列表
                $items = [];
                foreach ($detailsinfo as $key => $value) {
                    $item[$key]= new Item();
                    $item[$key]->setName($detailsinfo[$key]['product_name'])->setCurrency('HKD')
                                        ->setQuantity((int)$detailsinfo[$key]['product_number'])->setPrice((int)$detailsinfo[$key]['product_price']);
                    $items[] =$item[$key];
                }
                $itemList = new ItemList();
                $itemList->setItems($items);
            }
        }else{
            // 创建项目列表
            $BookMoney=(int)max( 0.01 , $orderinfo['booking_price']);
            $item = new Item();
            $item->setName('Order')->setCurrency('HKD')->setQuantity(1)->setPrice($BookMoney);
            $itemList = new ItemList();
            $itemList->setItems([$item]);
        }

        //设置订单地址
        if($orderinfo['delivery_address'] && $orderinfo['delivery_name'] && $orderinfo['delivery_phone']){
            $payeraddress = new ShippingAddress();
            $payeraddress->setRecipientName($orderinfo['delivery_name'])->setLine1($orderinfo['delivery_address'])
                                                                        ->setPhone($orderinfo['delivery_phone'])->setCountryCode('HK');
            $itemList->setShippingAddress($payeraddress);
        }
        // 创建一个新的折扣对象(不能用，所以把折扣金額變為負數，放稅收裡面)(**稅收不能為負數，所以把放運費裡面)
        // $discount = new Discount();
        // $discount->setCurrency('HKD')->setAmount($orderinfo['coupon_money'])->setDescription('discount'); // 设置折扣的整数值     
        //設置運費  支付金額
        $details = new Details();
        $details->setShipping($orderinfo['freight_price']-$orderinfo['coupon_money'])->setTax(0)->setSubtotal($orderinfo['original_cost']);
        //設置總金額  運費+產品支付-折扣金額
        $amount = new Amount();
        $amount->setCurrency("HKD")->setTotal($orderinfo['original_cost']+$orderinfo['freight_price']-$orderinfo['coupon_money'])->setDetails($details);
        // 设置重定向的URL
        $transaction = new Transaction();
        $transaction->setAmount($amount)->setItemList($itemList) ->setDescription("Payment description")->setInvoiceNumber(uniqid());
        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturnUrl($this->paypal_callback_success."?success=true&orderid=".$orderid)
                     ->setCancelUrl($this->paypal_callback_error."?success=false&orderid=".$orderid);
        // 创建支付
        $payment = new Payment();
        $payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array(array('amount' => $amount, 'item_list' => $itemList)));
        $payment->create($this->apiContext);
        //生成地址
        $approvalUrl = $payment->getApprovalLink();
        $result['orderId']=$orderid;
        $result['url']=$approvalUrl;
        return $result;
    }


    /**
     * @param Request $request
     * @return array
     * paypal支付回調-成功鏈接
     */
    public function PaypalCallbackSuccess(Request $request){
        $orderid = $request->get('orderid');//訂單ID
        $success = $request->get('success');
		$paymentId = $request->get('paymentId');//支付ID
		// $token   = $request->get('token'); //
        $PayerID=$request->get('PayerID');//支付人ID
        $orderinfo = Order::where('order_id',$orderid)->select('*')->first()->toArray();
        if (!empty($success)) {     
			$payment = Payment::get($paymentId, $this->apiContext);
			$execution = new PaymentExecution();
			$execution->setPayerId($PayerID);
            try {
                DB::beginTransaction();
                $result = $payment->execute($execution, $this->apiContext)->toArray();
                $orderRefundId = $result['transactions'][0]['related_resources'][0]['sale']['id'];
                // $this->LogInfo('paypal退款ID:' , $orderRefundId , 'PaypalCallback' , true);//开启日志记录
                //支付完成更改訂單信息
                $effects=$this->paymentComplete($orderid,$orderRefundId);// 支付完成更改訂單信息
                if(!empty($effects)){
                    //支付完成後操作(推送 郵箱 系統消息  )
                    $solution=$this->OrderComplete($orderid);
                    DB::commit();
                    //支付完成
                    if($this->language == "en" ){
                        return view('Payment/en_Success');
                    }else{
                        return view('Payment/Success');
                    }
                }else{
                    DB::rollBack();
                    // 支付不成功，退款
                    $Refund['refund_id']=$orderRefundId;//退款id
                    $Refund['order_money']=$orderinfo['order_money'];//退款金額
                    $returnInfo = $this->PayPalReturnMoney($Refund);
                    //支付失敗
                    if($this->language == "en" ){
                        return view('Payment/en_Error');
                    }else{
                        return view('Payment/Error');
                    }   
                }
            } catch (Exception $e) {
                //支付失敗
                if($this->language == "en" ){
                    return view('Payment/en_Error');
                }else{
                    return view('Payment/Error');
                }
            }
        } else {
            //支付失敗
            if($this->language == "en" ){
                return view('Payment/en_Error');
            }else{
                return view('Payment/Error');
            }
        }
    }



    /**
     * @param $data
     * @return array
     * PayPal退款
     */
    public function PayPalReturnMoney($data){
        try {
            $refund_id = $data['refund_id'];  //异步加调中拿到的id
            $amt = new Amount();
            $amt->setCurrency('HKD')->setTotal($data['order_money']);  // 退款的费用
            $refund = new Refund();
            $refund->setAmount($amt);
            $sale = new Sale();
            $sale->setId($refund_id);
            $refundedSale = $sale->refund($refund, $this->apiContext);
        } catch (\Exception $e) {
            // PayPal无效退款
            return false;

        }
        // 退款完成
        return true;
    }


    // /**
    //  * @param Request $request
    //  * @return array
    //  * paypal支付回調-失敗鏈接
    //  */
    // public function PaypalCallbackError(Request $request){

    // }

/**************************************************支付方式-Stripe支付*************************************************************************/
    /**
     * @param Request $request
     * @return array
     * 支付方式--Stripe支付
     * data['order_money']
     * data['user_id']
     * data['order_id']
     * data['payment_type']
     * 卡号  Visa:4242424242424242  4000000320000021 4000000760000002
     *测试卡号位置：https://docs.stripe.com/testing#international-cards
     */
    public function StripePayment(Request $request){
        $order_id = $request->get('order_id');//訂單ID
        $orderinfo = Order::where('order_id',$order_id)->select('*')->first()->toArray();
        $detailsinfo = OrderDetails::where('order_id',$order_id)->select('*')->get()->toArray();
        $user_id = $orderinfo['user_id'];//用户ID
        //查看有沒有該客戶，沒有就創建
        $UserInfo = $this->User->where('user_id',$user_id)->first();
        //修復stripe_id是空的時候報錯，只能是NULL
        if (empty($UserInfo['stripe_id'])) {
            $this->User->where('user_id',$UserInfo['user_id'])->update(['stripe_id'=>NULL]);
        }
        // 如果你想为给定的计费模型检索 Stripe 客户对象，但不确定该计费模型是否已经是 Stripe 中的客户，
        // 则可以使用 createOrGetStripeCustomer 方法。 如果尚不存在，此方法将在 Stripe 中创建一个新客户：
        $info['name']=$UserInfo['user_name'];
        $info['phone']=$orderinfo['delivery_phone'];
        $info['email']=$orderinfo['delivery_mail'];
        $stripeCustomer = $this->User->where('user_id',$user_id)->first()->createOrGetStripeCustomer($info);
        //創建完成
        // Stripe支付
        //产品金额(單位：分)
        $amount=($orderinfo['original_cost']+$orderinfo['freight_price']-$orderinfo['coupon_money']) * 100;//訂單金額+運費
        //Stripe支付最小金額為4元
        if($amount < 400 ){ 
            return $this->error(__('api.stripe_lowest'));
        }
        $name=$orderinfo['order_no'];//产品名称---現在顯示訂單號
        $quantity=1;//产品数量 
        $sessionOptions=[
            'mode'        => 'payment',
            'locale'      => 'zh-HK', //设置为繁体中文
            'success_url' => $this->stripe_callback_success."?success=true&orderid=".$order_id .'&session_id={CHECKOUT_SESSION_ID}',// 同步回调
            'cancel_url'  => $this->stripe_callback_error."?success=true&orderid=".$order_id,// 异步回调
            'metadata'    => [
                'order_id' => $order_id,
            ]
        ];
        $customerOptions=[
            'address'=>$orderinfo['delivery_address'],
            'email'=>$orderinfo['delivery_mail'],
            'phone'=>$orderinfo['delivery_phone']
        ];
        // $productData=[
        //     'name'=>'泳衣试穿',
        //     'images'  => ['https://brain-storm.oss-cn-hongkong.aliyuncs.com/2024-07-01/1719812892609821.png'],
        //     'description' => '手機簡介'
        // ];
        $UserCheckout=$this->User->where('user_id',$user_id)->first();
        $checkout =$UserCheckout->checkoutCharge($amount, $name, $quantity,$sessionOptions,$customerOptions,$productData=[]);
        return  $checkout;   
    }

    /**
     * @param Request $request
     * @return array
     * Stripe支付回調-成功鏈接
     */
    public function StripeCallbackSuccess(Request $request){
        $orderid = $request->get('orderid');//訂單ID
        $success = $request->get('success');
        $session_id = $request->get('session_id');
        try {
            DB::beginTransaction();
            //支付完成更改訂單信息
            $effects=$this->paymentComplete($orderid,$session_id);// 支付完成更改訂單信息
            if(!empty($effects)){
                //支付完成後操作(推送 郵箱 系統消息  )
                $solution=$this->OrderComplete($orderid);
                DB::commit();
                //支付完成
                if($this->language == "en" ){
                    return view('Payment/en_Success');
                }else{
                    return view('Payment/Success');
                }
            }else{
                DB::rollBack();
                // 支付不成功，退款
                // $returnInfo = $this->Striperefund($RefundId);
                //支付失敗
                if($this->language == "en" ){
                    return view('Payment/en_Error');
                }else{
                    return view('Payment/Error');
                }
            }
        } catch (Exception $e) {
            //支付失敗
            if($this->language == "en" ){
                return view('Payment/en_Error');
            }else{
                return view('Payment/Error');
            }
        }
    }

    /**
     * @param Request $request
     * @return array
     * 退还费用
     */
    public function Striperefund(Request $request) {
        $Striperefund=1;
        return $Striperefund;
    }

    
    /**
     * @param Request $request
     * @return array
     * Stripe支付回調-成功鏈接
     */
    public function StripeCallbackError(Request $request){
            //支付失敗
            if($this->language == "en" ){
                return view('Payment/en_Error');
            }else{
                return view('Payment/Error');
            }
    }

/**************************************************支付方式-其他支付*************************************************************************/
    /**
     * @param Request $request
     * @return array
     * 支付方式--其他支付
     * data['order_money']
     * data['user_id']
     * data['order_id']
     * data['payment_type']
     */
    public function OtherPayment($data){
        
    }


/**************************************************支付完成訂單修改****************************************************************************/
    /**
     * @param Request $request
     * @return array
     * 支付完成訂單修改
     */
    public function paymentComplete($orderId,$refundId=''){
        DB::beginTransaction();
        try {
            //更新訂單信息
            $updateOrder=Order::where('order_id',$orderId)->update(['payment_status'=> 3 , 'return_status'=> 1, 'refund_id'=>$refundId ,  'push_state' => 1,  
                                                                    'payment_at'=>date('Y-m-d H:i:s'),  'mail_state' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
            //查詢訂單詳情信息
            $details = OrderDetails::where('order_id',$orderId)->select('details_id','user_id','product_number','product_id','product_relation_id','product_type')->get()->toArray();
            $OrderInfo=Order::where('order_id',$orderId)->select('payment_mode','payment_type','order_money')->first()->toArray();
            if(!empty($details)){
                //更新庫存
                foreach ($details as $key => $value) {
                    $user_id=$details[$key]['user_id']; //用户id    
                    $details_id=$details[$key]['details_id']; //訂單詳情id   
                    $product_id=$details[$key]['product_id']; //產品id  
                    $product_type=$details[$key]['product_type'];  //產品類型  1：產品 2：服務   
                    $product_number=$details[$key]['product_number'];  //購買數量   
                    $product_relation_id=$details[$key]['product_relation_id']; //產品規格組合id
                    //產品就修改庫存,預約就不變
                    if($product_type==1 && $OrderInfo['payment_type']==1){
                        $ProductStock=Product::where('product_id',$product_id)->decrement('product_stock',$product_number);
                        $RelationStock=ProductRelation::where('product_relation_id',$product_relation_id)->decrement('stock',$product_number);
                    }
                    //更新用户积分情况
                    $ProdunctInfo=Product::where('product_id',$product_id)->select('integral_num','is_integral')->first()->toArray();
                    $integral_num=$ProdunctInfo['integral_num'];
                    $is_integral=$ProdunctInfo['is_integral'];
                    if(!empty($is_integral)){
                        $UserIntegral=User::where('user_id',$user_id)->increment('user_integral',$integral_num);
                        $UserIntegralAll=User::where('user_id',$user_id)->increment('user_integral_all',$integral_num);
                        //积分记录
                        $IntegralInfo = [
                            'user_id' => $user_id,
                            'integral_type' => 1,
                            'integral_explain'=>'購買商品贈送積分',
                            'en_integral_explain'=>'Purchase items and get bonus points',
                            'integral_number' => $integral_num,
                            'created_at' => date('Y-m-d H:i:s'),
                            'updated_at' => date('Y-m-d H:i:s')
                        ];
                        UserIntegralRecord::insert($IntegralInfo);
                    }   
                }  
            }
            //添加钱包记录
            $WalletInfo = [
                'user_id' => $user_id,
                'wallet_type' => 1,
                'payment_mode' => $OrderInfo['payment_mode'],
                'wallet_explain'=>'購買商品',
                'en_wallet_explain'=>'purchase commodity',
                'wallet_money' => $OrderInfo['order_money'],
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
            $effects=UserWalletRecord::insert($WalletInfo);
            if(!empty($effects)){
                // $this->LogInfo('添加钱包记录' , $WalletInfo , 'UserWalletRecord' , true);//开启日志记录
                DB::commit();   return $effects;
            }else{
                DB::rollBack();   return false;
            }
        }catch (\Exception $e) {
            DB::rollBack();   return  $e->getMessage();
        }       
    }


/**************************************************支付成功後的推送發送丶郵件發送丶個推發送，系統消息發送************************************************/
    /**
     * @param Request $request
     * @return array
     * 支付成功後的推送發送丶郵件發送丶個推發送，系統消息發送
     */
    public function OrderComplete($orderId){
        $OrderInfo = Order::where('order_id',$orderId)->first();
        $UserInfo = User::where('user_id',$OrderInfo['user_id'])->select('user_id','client_id','token_type')->first();
        if($OrderInfo['indent_type']==1){
            $Message = '您的訂單：'.$OrderInfo['order_no'].',已經訂購成功,我們將盡快為您處理！';
            $en_Message = 'Your order: '.$OrderInfo['order_no'].',has been ordered successfully, we will deal with you as soon as possible!';
        }else{
            $Message = '您的訂單：'.$OrderInfo['order_no'].',已經成功預約，時間為：'.$OrderInfo['order_time'];
            $en_Message = 'Your order: '.$OrderInfo['order_no'].', has been successfully booked, time: '.$OrderInfo['order_time'];
        }
        try {
            if(!empty($OrderInfo)){
                //加入系統消息
                $SystemInfo = new SystemInfo();
                $code=$SystemInfo->addSystemInfo($UserInfo['user_id'], $OrderInfo['indent_type'], $Message, $en_Message);
                if(!empty($code)){
                    $SendMessage= $this->language == "en" ? $en_Message : $Message;
                    if(!empty($OrderInfo['delivery_mail'])){
                        //邮箱推送
                        $EmailInfo['Email']=$OrderInfo['delivery_mail'];
                        $EmailInfo['Message']=$SendMessage;
                        $mail = new MailController();
                        $mail->MessageEmails($EmailInfo);
                    }
                    //加入推送消息
                    if(!empty($UserInfo['client_id'])){
                        $GeTui = new GeTuiController();
                        @$PushInfo = $GeTui->pushToSingleByCid($UserInfo['client_id'],$SendMessage,$SendMessage, 1);
                        //更新訂單信息
                        Order::where('order_id',$orderId)->update([ 'push_state' => 2, 'mail_state' => 2,'updated_at'=>date('Y-m-d H:i:s')]);
                        // $this->LogInfo('推送消息' , $PushInfo , 'PushInfo' , true);//开启日志记录
                    }
                }
            }
        }catch (\Exception $e) {
            // return  $e->getMessage();
        }
    }




    
    

/**************************************************end****************************************************************************/
}
